package com.maxd.service.userinfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.google.common.collect.Maps;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.modules.member.dao.MemberRepository;
import com.maxd.modules.member.entity.Member;
import com.maxd.modules.member.service.IMemberService;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.msg.MsgJpaRepository;
import com.maxd.respository.token.TokenJpaRepository;
import com.maxd.respository.token.TokenRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.message.IMessageService;
import com.maxd.service.wx.AccountService;
import com.maxd.utils.*;
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsPidGenerateRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsPidQueryRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsPidGenerateResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.JsonResponseModel;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.user.User;
import weixin.popular.util.JsonUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户的service实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TokenJpaRepository tokenJpaRepository;
    @Autowired
    private TokenRepository tokenRepository;
    @Autowired
    private MsgJpaRepository msgJpaRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IUserLogService iUserLogService;
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private IMemberService memberService;

    private int number = 1;

    @Override
    public Result findAll() {
        return ResultUtil.success(userJpaRepository.findAll());
    }

    @Override
    public Result saveBody(UserInfo userInfo) {
        userJpaRepository.save(userInfo);
        return ResultUtil.success();
    }

    @Override
    public Result bindOpenId(String userId, String openId) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        if (one != null) {
            UserInfo save = getWx(openId, one);
            return ResultUtil.success(save);
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    @Override
    public Result loginTb(LoginInfo loginInfo) {
        UserInfo one = userRepository.getUserByTbOpenid(loginInfo.getOpenid());
        if (one != null) {
            one.setImage_url(loginInfo.getImageUrl());
            if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                one.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            }
            return getResult(userJpaRepository.save(one));
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    @Override
    public Result loginApp(LoginInfo loginInfo) {
        if (StringUtils.isNotBlank(loginInfo.getUnionid())) {
            UserInfo one = userRepository.getUserByUnionid(loginInfo.getUnionid());
            if (one != null) {
                String s = HttpClient.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + loginInfo.getToken() + "&openid=" + loginInfo.getOpenid());
                AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
                if (user != null && user.getNickname() != null) {
                    if (user.getHeadimgurl() != null) {
                        one.setImage_url(user.getHeadimgurl());
                    }
                    if (user.getCity() != null) {
                        one.setAddress(user.getCity());
                    }
                    one.setGender(String.valueOf(user.getSex()));
                    if (user.getNickname() != null) {
                        one.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                }
                return getResult(userJpaRepository.save(one));
            } else {
                return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
            }
        } else if (StringUtils.isNotBlank(loginInfo.getOpenid())) {
            UserInfo one = userRepository.getUserByWxId(loginInfo.getOpenid());
            if (one != null) {
                String s = HttpClient.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + loginInfo.getToken() + "&openid=" + loginInfo.getOpenid());
                AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
                if (user != null && user.getNickname() != null) {
                    if (user.getHeadimgurl() != null) {
                        one.setImage_url(user.getHeadimgurl());
                    }
                    if (user.getCity() != null) {
                        one.setAddress(user.getCity());
                    }
                    one.setGender(String.valueOf(user.getSex()));
                    if (user.getNickname() != null) {
                        one.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                }
                return getResult(userJpaRepository.save(one));
            } else {
                return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
            }
        } else {
            return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
        }
    }

    @Override
    public Result bindTaoBao(LoginInfo loginInfo) {
        UserInfo userInfo = userJpaRepository.getOne(Long.valueOf(loginInfo.getUserId()));
        UserInfo one = userRepository.getUserByTbOpenid(loginInfo.getOpenid());
        if (userInfo == null) {
            return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
        }
        if (userInfo.getTb_openid() != null) {
            return ResultUtil.error(ExceptionEnum.IS_BIND_RELATION);
        }
        if (one != null) {
            return ResultUtil.error(ExceptionEnum.IS_BIND);
        }
        userInfo.setTb_openid(loginInfo.getOpenid());
        userInfo.setImage_url(loginInfo.getImageUrl());
        if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
            userInfo.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
        }
        return getResult(userJpaRepository.save(userInfo));
    }

    @Override
    public Result sendMsg(String phone, String state) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println("sendMsg code is " + code);
        if (state.equals("forget")) {
            UserInfo userByPhone = userRepository.getUserByPhone(phone);
            if (userByPhone == null) {
                return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
            }
        }
        if (state.equals("bind")) {
            UserInfo userByPhone = userRepository.getUserByPhone(phone);
            if (userByPhone != null) {
                return ResultUtil.error(ExceptionEnum.USER_IS_EXITS);
            }
        }
        if (state.equals("register")) {
            UserInfo userByPhone = userRepository.getUserByPhone(phone);
            if (userByPhone != null) {
                return ResultUtil.error(ExceptionEnum.USER_IS_REGISTER);
            }
        }
        if (state.equals("bindWx")) {
            UserInfo userByPhone = userRepository.getUserByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getOpen_uid())) {
                return ResultUtil.error(ExceptionEnum.USER_IS_BIND_FOR_ANTHER_OPENID);
            }
        }
        CommonInfo three = commonRepository.findOne(163);
        //默认使用腾讯云
        if (three == null || "1".equals(three.getValue())) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code);
        } else if ("2".equals(three.getValue())) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, state, code);
        } else {
            return sendMsgDXB(phone, state, code);
        }
    }

    private Result sendMsgAlibaba(String phone, String state, int code) {

        CommonInfo three = commonRepository.findOne(83);
        String accessKeyId = three.getValue();
        CommonInfo four = commonRepository.findOne(84);
        String accessSecret = four.getValue();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonInfo one = commonRepository.findOne(12);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", one.getValue());
        String value;
        switch (state) {
            case "register":
                value = commonRepository.findOne(80).getValue();
                break;
            case "forget":
                value = commonRepository.findOne(81).getValue();
                break;
            case "bind":
                value = commonRepository.findOne(82).getValue();
                break;
            default:
                value = commonRepository.findOne(80).getValue();
                break;
        }
        request.putQueryParameter("TemplateCode", value);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String data = response.getData();
            JSONObject jsonObject = JSON.parseObject(data);
            if ("OK".equals(jsonObject.get("Code"))) {
                Msg byPhone = msgJpaRepository.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgJpaRepository.save(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgJpaRepository.save(msg);
                }
                UserInfo userByPhone = userRepository.getUserByPhone(phone);
                if (userByPhone != null) {
                    return ResultUtil.success("login");
                } else {
                    return ResultUtil.success("register");
                }
            } else {
                if ("GB:0001".equals(jsonObject.get("Code").toString()) || "GB:0002".equals(jsonObject.get("Code").toString()) || "GB:0003".equals(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "短信发送过于频繁，请稍后再试！");
                } else if ("MA:0021".equals(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "手机号格式错误！");
                } else if ("isv.MOBILE_NUMBER_ILLEGAL".equals(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "手机号格式错误！");
                } else if ("分钟".contains(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "短信发送过于频繁，请一分钟后再试！");
                } else if ("小时".contains(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "短信发送过于频繁，请一小时后再试！");
                } else if ("天".contains(jsonObject.get("Code").toString())) {
                    return ResultUtil.error(-1, "短信发送过于频繁，请明天再试！");
                }
//                log.info(jsonObject.get("Message").toString());
                return ResultUtil.error(ExceptionEnum.SEND_ERROR);
                //return ResultUtil.error(6, jsonObject.get("Message").toString());
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ExceptionEnum.SEND_ERROR);
    }


    private Result sendMsgTencent(String phone, String state, int code) {
        SmsSingleSenderResult result = null;

        CommonInfo three = commonRepository.findOne(31);
        String clientId = Config.DXAppId;
        if (three != null) {
            clientId = three.getValue();
        }
        CommonInfo four = commonRepository.findOne(32);
        String clientSecret = Config.DXAppKey;
        if (four != null) {
            clientSecret = four.getValue();
        }
        try {
            String secretId = commonRepository.findOne(257).getValue();
            String secretKey = commonRepository.findOne(258).getValue();
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {phone};
            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(clientId);
            CommonInfo one = commonRepository.findOne(12);
            req.setSignName(one.getValue());
            switch (state) {
                case "register":
                    req.setTemplateId(commonRepository.findOne(259).getValue());
                    break;
                case "forget":
                    req.setTemplateId(commonRepository.findOne(260).getValue());
                    break;
                case "bind":
                    req.setTemplateId(commonRepository.findOne(261).getValue());
                    break;
                default:
                    req.setTemplateId(commonRepository.findOne(259).getValue());
                    break;
            }
            String[] templateParamSet1 = {String.valueOf(code)};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            JSONObject jsonObject = JSONObject.parseObject(SendSmsResponse.toJsonString(resp));
            JSONArray sendStatusSet = jsonObject.getJSONArray("SendStatusSet");
            JSONObject jsonObject1 = sendStatusSet.getJSONObject(0);
            if ("Ok".equals(jsonObject1.getString("Code"))) {
                Msg byPhone = msgJpaRepository.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgJpaRepository.save(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgJpaRepository.save(msg);
                }
                UserInfo userByPhone = userRepository.getUserByPhone(phone);
                if (userByPhone != null) {
                    return ResultUtil.success("login");
                } else {
                    return ResultUtil.success("register");
                }
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return ResultUtil.error(6, result.errMsg);
    }


    private Result sendMsgDXB(String phone, String state, int code) {
        CommonInfo three = commonRepository.findOne(164);
        CommonInfo four = commonRepository.findOne(165);
        CommonInfo one = commonRepository.findOne(12);
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        String value = "";
        switch (state) {
            case "register":
                value = "【" + one.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "forget":
                value = "【" + one.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "bind":
                value = "【" + one.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            default:
                value = "【" + one.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
        }
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request(Config.DXBUrl, httpArg.toString());
        log.error("短信包返回值：" + result);
        if ("0".equals(result)) {
            Msg byPhone = msgJpaRepository.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(code));
                byPhone.setPhone(phone);
                msgJpaRepository.save(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(code));
                msg.setPhone(phone);
                msgJpaRepository.save(msg);
            }
            UserInfo userInfoByPhone = userRepository.getUserByPhone(phone);
            if (userInfoByPhone != null) {
                return ResultUtil.success("login");
            } else {
                return ResultUtil.success("register");
            }
        } else {
//            return ResultUtil.error(6, result.errMsg);
            if ("30".equals(result)) {
                return ResultUtil.error(-200, "错误密码");
            } else if ("40".equals(result)) {
                return ResultUtil.error(-200, "账号不存在");
            } else if ("41".equals(result)) {
                return ResultUtil.error(-200, "余额不足");
            } else if ("43".equals(result)) {
                return ResultUtil.error(-200, "IP地址限制");
            } else if ("50".equals(result)) {
                return ResultUtil.error(-200, "内容含有敏感词");
            } else if ("51".equals(result)) {
                return ResultUtil.error(-200, "手机号码不正确");
            }
        }

        return ResultUtil.error(ExceptionEnum.SEND_ERROR);
    }

    @Override
    public Result getUsersByInvitation(String invitation, Pageable pageable) {
        return ResultUtil.success(userRepository.getUsersByInvitation(invitation, pageable));
    }

    @Override
    public Result getInvitation(String invitation) {
        return ResultUtil.success(userRepository.getInvitation(invitation));
    }

    @Override
    public Result getCount(String invitation) {
        return ResultUtil.success(userRepository.getCount(invitation));
    }

    @Override
    public Result getCash(String invitation) {
        List<UserInfo> invitation1 = userRepository.getInvitation(invitation);
        for (UserInfo userInfo : invitation1) {
            synchronized (SingleByUserId.getById(userInfo.getRelationId())) {
                userInfo.setBalance(1);
                userJpaRepository.save(userInfo);
            }
        }
        UserInfo userByRelationId = userRepository.getUserByRelationId(invitation);
        String value = String.valueOf(invitation1.size());
        double a = Double.parseDouble(value) + Double.parseDouble(userByRelationId.getJifen());
        System.out.println("getCash is " + a);
        userByRelationId.setJifen(String.valueOf(a));
        return ResultUtil.success(userJpaRepository.save(userByRelationId));
    }

    //非线程安全实现，需要修改
    static class SingleByUserId {
        static Map<String, Object> map = new HashMap<>();

        static Object getById(String userId) {
            if (map.get(userId) != null) {
                return map.get(userId);
            } else {
                Object object = new Object();
                map.put(userId, object);
                return object;
            }
        }
    }

    @Override
    public Result bindOpenid(LoginInfo loginInfo) {
        CommonInfo one = commonRepository.findOne(4);
        Msg byPhoneAndCode = msgJpaRepository.findByPhoneAndCode(loginInfo.getPhone(), loginInfo.getMsg());
        if (byPhoneAndCode == null) {
            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
        }
        msgJpaRepository.deleteById(byPhoneAndCode.getId());
        //如果openid可以获取到用户信息 检查输入的手机号和openid绑定的手机号是不是一样
        UserInfo userByWxId = userRepository.getUserByWxId(loginInfo.getOpenid());
        if (userByWxId != null) {
            UserInfo userByPhone1 = userRepository.getUserByPhone(loginInfo.getPhone());
            if (userByPhone1 == null) {
                if (StringUtils.isEmpty(userByWxId.getPhone())) {
                    userByWxId.setPhone(loginInfo.getPhone());
                    userJpaRepository.save(userByWxId);
                    return getResult(userByWxId);
                } else {
                    loginInfo = isInvitaionCode(one, loginInfo);
                    if (loginInfo == null) {
                        return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
                    }
                    return saveInfo(loginInfo.getPhone(), loginInfo.getOpenid(), loginInfo.getInvitation(), loginInfo.getPwd(), loginInfo.getPlatform());
                }
            } else {
                if (StringUtils.isEmpty(userByPhone1.getOpenId())) {
                    userByPhone1.setOpenId(loginInfo.getOpenid());
                    userJpaRepository.save(userByPhone1);
                    return getResult(userByPhone1);
                } else {
                    return getResult(userByPhone1);
                }
            }
            //如果俩手机号一样 执行登录操作
            /*if (userByWxId.getPhone() != null && userByWxId.getPhone().equals(loginInfo.getPhone())) {
                msgJpaRepository.deleteById(byPhoneAndCode.getId());
                return getResult(userByWxId);
            } else {
                //没有绑定手机号 执行绑定手机号的操作
                *//*if (userByWxId.getPhone() != null) {
                    //俩手机号不一样执行 提示操作
                    return ResultUtil.error(8, "当前微信已经被【" + userByWxId.getPhone() + "】账号绑定，如有疑问请联系客服");
                }*//*
                userByWxId.setPhone(loginInfo.getPhone());
                if (StringUtils.isNotBlank(loginInfo.getInvitation())) {
                    if (loginInfo.getInvitation().length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                        userByWxId.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userByWxId.setInvitation(loginInfo.getInvitation());
                    }
                } else {
                    if (one.getValue().length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                        userByWxId.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userByWxId.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                    }
                }
                userByWxId.setZhifubao(loginInfo.getPhone());
                msgJpaRepository.deleteById(byPhoneAndCode.getId());
                return getResult(userJpaRepository.save(userByWxId));
            }*/
        } else {
            //校验手机号是否注册
            UserInfo userByPhone = userRepository.getUserByPhone(loginInfo.getPhone());
            if (userByPhone == null) {
                loginInfo = isInvitaionCode(one, loginInfo);
                if (loginInfo == null) {
                    return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
                }
                return saveInfo(loginInfo.getPhone(), loginInfo.getOpenid(), loginInfo.getInvitation(), loginInfo.getPwd(), loginInfo.getPlatform());
            } else {
                if (StringUtils.isEmpty(userByPhone.getOpenId())) {
                    userByPhone.setOpenId(loginInfo.getOpenid());
                    userJpaRepository.save(userByPhone);
                }
                return getResult(userByPhone);
            }
        }
    }

    private LoginInfo isInvitaionCode(CommonInfo one, LoginInfo loginInfo) {
        if (!one.getValue().equals("0")) {
            int length = loginInfo.getInvitation().length();
            UserInfo userByRelationId;
            if (length == 6) {
                userByRelationId = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
            } else {
                userByRelationId = userRepository.getUserByRelationId(loginInfo.getInvitation());
            }
            if (userByRelationId == null) {
                return null;
            }
            loginInfo.setInvitation(userByRelationId.getRelationId());
        }
        return loginInfo;
    }


    //保存用户信息
    private Result saveInfo(String phone, String openid, String invitation, String pwd, String platform) {
        CommonInfo one = commonRepository.findOne(4);
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(strDateFormat);
        String time = simpleDateFormat.format(new Date());
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setPhone(phone);
        if (StringUtils.isNotEmpty(phone)) {
            userInfo1.setNickName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
        }
        userInfo1.setGrade(commonRepository.findOne(40).getValue());
        UserInfo save;
        if (StringUtils.isNotBlank(invitation)) {
            if (invitation.length() == 6) {
                UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(invitation);
                userInfo1.setInvitation(userByInvitationCode.getRelationId());
            } else {
                userInfo1.setInvitation(invitation);
            }
            userInfo1.setIsInvitation(1);
            userInfo1.setJifen("0");
            userInfo1.setOrderJifen("0");
            userInfo1.setPwd(MD5Util.encoderByMd5(pwd));
            userInfo1.setPlatform(platform);
            userInfo1.setZhifubao(phone);
            userInfo1.setCreateAt(time);
            userInfo1.setState("true");
            save = getWx(openid, userInfo1);
            checkRelationInvitation(invitation, userInfo1.getNickName());
        } else {
            if (one.getValue().length() == 6) {
                UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                userInfo1.setInvitation(userByInvitationCode.getRelationId());
            } else {
                userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
            }
            userInfo1.setIsInvitation(1);
            userInfo1.setJifen("0");
            userInfo1.setOrderJifen("0");
            userInfo1.setPwd(MD5Util.encoderByMd5(pwd));
            userInfo1.setPlatform(platform);
            userInfo1.setZhifubao(phone);
            userInfo1.setCreateAt(time);
            userInfo1.setState("true");
            save = getWx(openid, userInfo1);
        }
        return getResult(save);
    }

    /**
     * 获取微信详情
     *
     * @param openid
     * @param userInfo
     * @return
     */
    private UserInfo getWx(String openid, UserInfo userInfo) {
        User wx = accountService.getUserInfo(openid);
        if (wx.getHeadimgurl() != null) {
            userInfo.setImage_url(wx.getHeadimgurl());
        }
        if (wx.getSex() != null) {
            userInfo.setGender(String.valueOf(wx.getSex()));
        }
        if (wx.getCity() != null) {
            userInfo.setAddress(wx.getCity());
        }
        if (wx.getNickname() != null) {
            userInfo.setNickName(wx.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
        }
        userInfo.setOpenId(openid);
        return userJpaRepository.saveAndFlush(userInfo);
    }

    @Override
    public Result loginTaoBao(LoginInfo loginInfo) {
        CommonInfo one = commonRepository.findOne(4);
        Msg msg1 = msgJpaRepository.findByPhoneAndCode(loginInfo.getPhone(), loginInfo.getMsg());
        //校验短信验证码
        if (msg1 == null) {
            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
        }
        //校验手机号是否存在
        UserInfo userInfo = userRepository.getUserByPhone(loginInfo.getPhone());
        if (userInfo != null) {
            if (userInfo.getTb_openid() != null) {
                return ResultUtil.error(ExceptionEnum.BIND_ERROR);
            } else {
                userInfo.setTb_openid(loginInfo.getOpenid());
                userInfo.setImage_url(loginInfo.getImageUrl());
                if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                    userInfo.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                UserInfo save = userJpaRepository.save(userInfo);
                msgJpaRepository.deleteById(msg1.getId());
                return getResult(save);
            }
        } else {
            loginInfo = isInvitaionCode(one, loginInfo);
            if (loginInfo == null) {
                return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(loginInfo.getPhone());
            if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                userInfo1.setNickName(loginInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            }
            UserInfo save;
            if (loginInfo.getInvitation() != null) {
                if (loginInfo.getInvitation().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(loginInfo.getInvitation());
                }
                userInfo1.setPwd(MD5Util.encoderByMd5(loginInfo.getPwd()));
                userInfo1.setIsInvitation(1);
                userInfo1.setJifen("0");
                userInfo1.setPlatform(loginInfo.getPlatform());
                userInfo1.setOrderJifen("0");
                userInfo1.setTb_openid(loginInfo.getOpenid());
                userInfo1.setGrade(commonRepository.findOne(40).getValue());
                userInfo1.setZhifubao(loginInfo.getPhone());
                userInfo1.setCreateAt(time);
                userInfo1.setImage_url(loginInfo.getImageUrl());
                if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                    userInfo1.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                userInfo1.setState("true");
                save = userJpaRepository.saveAndFlush(userInfo1);
                checkRelationInvitation(loginInfo.getInvitation(), userInfo1.getNickName());
            } else {
                if (one.getValue().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                }
                userInfo1.setPwd(MD5Util.encoderByMd5(loginInfo.getPwd()));
                userInfo1.setIsInvitation(1);
                userInfo1.setJifen("0");
                userInfo1.setPlatform(loginInfo.getPlatform());
                userInfo1.setOrderJifen("0");
                userInfo1.setTb_openid(loginInfo.getOpenid());
                userInfo1.setGrade(commonRepository.findOne(40).getValue());
                userInfo1.setZhifubao(loginInfo.getPhone());
                userInfo1.setCreateAt(time);
                userInfo1.setImage_url(loginInfo.getImageUrl());
                if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                    userInfo1.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                userInfo1.setState("true");
                save = userJpaRepository.saveAndFlush(userInfo1);
            }
            msgJpaRepository.deleteById(msg1.getId());
            return getResult(save);
        }
    }

    @Override
    public Result loginWeiXinApp(LoginInfo loginInfo) {
        CommonInfo one = commonRepository.findOne(4);
        Msg msg1 = msgJpaRepository.findByPhoneAndCode(loginInfo.getPhone(), loginInfo.getMsg());
        //校验短信验证码
        if (msg1 == null) {
            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
        }
        //校验手机号是否存在
        UserInfo userInfo = userRepository.getUserByPhone(loginInfo.getPhone());
        if (userInfo != null) {
            if (StringUtils.isNotBlank(userInfo.getOpen_uid())) {
                return ResultUtil.error(ExceptionEnum.BIND_ERROR);
            } else {
                String s = HttpClient.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + loginInfo.getToken() + "&openid=" + loginInfo.getOpenid());
                AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
                if (user != null && user.getNickname() != null) {
                    if (user.getHeadimgurl() != null) {
                        userInfo.setImage_url(user.getHeadimgurl());
                    }
                    if (user.getCity() != null) {
                        userInfo.setAddress(user.getCity());
                    }
                    userInfo.setGender(String.valueOf(user.getSex()));
                    if (user.getNickname() != null) {
                        userInfo.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                }
                userInfo.setOpen_uid(loginInfo.getOpenid());
                userInfo.setUnionid(loginInfo.getUnionid());
                UserInfo save = userJpaRepository.save(userInfo);
                msgJpaRepository.deleteById(msg1.getId());
                return getResult(save);
            }
        } else {
            loginInfo = isInvitaionCode(one, loginInfo);
            if (loginInfo == null) {
                return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(loginInfo.getPhone());
            if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                userInfo1.setNickName(loginInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            }

            if (loginInfo.getInvitation() != null) {
                if (loginInfo.getInvitation().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(loginInfo.getInvitation());
                }
            } else {
                if (one.getValue().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                }
            }
            userInfo1.setPwd(MD5Util.encoderByMd5(loginInfo.getPwd()));
            userInfo1.setIsInvitation(1);
            userInfo1.setJifen("0");
            userInfo1.setPlatform(loginInfo.getPlatform());
            userInfo1.setOrderJifen("0");
            userInfo1.setUnionid(loginInfo.getUnionid());
            userInfo1.setOpen_uid(loginInfo.getOpenid());
            userInfo1.setGrade(commonRepository.findOne(40).getValue());
            userInfo1.setZhifubao(loginInfo.getPhone());
            userInfo1.setCreateAt(time);
            String s = HttpClient.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + loginInfo.getToken() + "&openid=" + loginInfo.getOpenid());
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo1.setImage_url(user.getHeadimgurl());
                }
                if (user.getCity() != null) {
                    userInfo1.setAddress(user.getCity());
                }
                userInfo1.setGender(String.valueOf(user.getSex()));
                if (user.getNickname() != null) {
                    userInfo1.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            userInfo1.setState("true");
            UserInfo save = userJpaRepository.saveAndFlush(userInfo1);
            if (loginInfo.getInvitation() != null) {
                checkRelationInvitation(loginInfo.getInvitation(), userInfo1.getNickName());
            }
            msgJpaRepository.deleteById(msg1.getId());
            return getResult(save);
        }
    }


    @Override
    public Result loginCode(LoginInfo loginInfo) {
        CommonInfo one = commonRepository.findOne(4);
        Msg msg1 = msgJpaRepository.findByPhoneAndCode(loginInfo.getPhone(), loginInfo.getMsg());
        //校验短信验证码
        if (msg1 == null) {
            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
        }
        //校验手机号是否存在
        UserInfo userInfo = userRepository.getUserByPhone(loginInfo.getPhone());
        if (userInfo != null) {
//            msgJpaRepository.deleteById(msg1.getId());
            return getResult(userInfo);
        } else {
            loginInfo = isInvitaionCode(one, loginInfo);
            if (loginInfo == null) {
                return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(loginInfo.getPhone());
            if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                userInfo1.setNickName(loginInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            }
            if (!StringUtils.isEmpty(loginInfo.getInvitation())) {
                if (loginInfo.getInvitation().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(loginInfo.getInvitation());
                }
            } else {
                if (one.getValue().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                    userInfo1.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                }
            }
            userInfo1.setPwd(MD5Util.encoderByMd5(loginInfo.getPwd()));
            userInfo1.setIsInvitation(1);
            userInfo1.setJifen("0");
            userInfo1.setPlatform(loginInfo.getPlatform());
            userInfo1.setOrderJifen("0");
            userInfo1.setGrade(commonRepository.findOne(40).getValue());
            userInfo1.setZhifubao(loginInfo.getPhone());
            userInfo1.setCreateAt(time);
            userInfo1.setState("true");
            userInfo1.setAppleUserId(loginInfo.getAppleUserId());
            UserInfo save = userJpaRepository.saveAndFlush(userInfo1);
            if (!StringUtils.isEmpty(loginInfo.getInvitation())) {
                checkRelationInvitation(loginInfo.getInvitation(), userInfo1.getNickName());
            }
            msgJpaRepository.deleteById(msg1.getId());
            return getResult(save);
        }
    }


    @Override
    public Result bindPhone(String userId, String phone, String code) {
        UserInfo one = userJpaRepository.getOne(Long.valueOf(userId));
        if (one == null) {
            return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
        }
        UserInfo userInfo = userRepository.getUserByPhone(phone);
        if (userInfo != null && userInfo.getOpenId() != null) {
            return ResultUtil.error(ExceptionEnum.USER_IS_BIND_FOR_ANTHER_OPENID);
        }
        Msg byPhoneAndCode = msgJpaRepository.findByPhoneAndCode(phone, code);
//        if (byPhoneAndCode == null) {
//            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
//        }
        one.setPhone(phone);
        one.setZhifubao(phone);
        return ResultUtil.success(userJpaRepository.save(one));
    }


    @Override
    public Result updatePhone(String phone, String msg, String userId) {
        Msg msg1 = msgJpaRepository.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 != null) {
            UserInfo userInfo = userRepository.getUserByPhone(phone);
            if (userInfo != null) {
                return ResultUtil.error(ExceptionEnum.BIND_ERROR);
            } else {
                UserInfo one = userJpaRepository.getOne(Long.valueOf(userId));
                one.setPhone(phone);
                return ResultUtil.success(userJpaRepository.save(one));
            }
        }
        return ResultUtil.error(ExceptionEnum.CODE_ERROR);
    }


    @Override
    public Result bindRelationId(String userId, String relationId) {
        try {
            UserInfo userByRelationId;
            if (relationId.length() == 6) {
                userByRelationId = userRepository.getUserByInvitationCode(relationId);
            } else {
                userByRelationId = userRepository.getUserByRelationId(relationId);
            }
            if (userByRelationId != null) {
                return ResultUtil.error(ExceptionEnum.RELATIONID_IS_REGISTER);
            }
            UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
            if (one != null) {
                one.setIsRelation(1);
                one.setRelationId(relationId);
                UserInfo save = userJpaRepository.save(one);
                if (one.getOpenId() != null) {
                    bindRelationSucces(one.getOpenId(), one.getNickName(), relationId);
                }
                return ResultUtil.success(save);
            }
            return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    /**
     * 加入会员通知
     */
    private void bindRelationSucces(String openId, String name, String number) {
        UserInfo userByWxId = userRepository.getUserByWxId(openId);
        //后台服务域名配置
        CommonInfo url = commonRepository.findOne(19);
        //获取全局名称
        CommonInfo four = commonRepository.findOne(12);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(5));
        messageInfo.setContent(name + " 恭喜你！成为" + four.getValue() + "会员！会员号【" + number + "】!您已拥有会员多项特权，点击查看详情进入会员中心，生成专属链接邀请好友可提升佣金哦");
        messageInfo.setTitle("成为会员提醒");
        messageInfo.setUserName(userByWxId.getNickName());
        messageInfo.setUserId(String.valueOf(userByWxId.getId()));
        iMessageService.saveBody(messageInfo);
        if (userByWxId.getClientid() != null) {
            pushToSingle("成为会员提醒", name + " 恭喜你！成为" + four.getValue() + "会员！会员号【" + number + "】!您已拥有会员多项特权，点击查看详情进入会员中心，生成专属链接邀请好友可提升佣金哦", userByWxId.getClientid());
        }
        CommonInfo three = commonRepository.findOne(36);
        String apkey = Config.RelationNotification;
        if (three != null) {
            apkey = three.getValue();
        }

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
        data.put("thing2", new TemplateMessageItem("恭喜你！成为" + four.getValue() + "会员", "#d71345"));
        data.put("thing9", new TemplateMessageItem(name, "#d71345"));
        accountService.sendWxMessage(apkey, data, openId, url.getValue() + "/pages/member/user");
    }

    @Override
    public Result bindRelationIdCode(String userId, String relationId, String code) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        if (one != null) {
            one.setRelationId(relationId);
            one.setInvitation(code);
            UserInfo save = userJpaRepository.save(one);
            return ResultUtil.success(save);
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    private static Integer status = 0;


    /**
     * 检查所有用户 重新生成邀请码
     *
     * @return
     */
    @Override
    public Result updateInvitationCode() {
        if (status == 0) {
            List<UserInfo> all = userRepository.selectUserList();
            for (UserInfo userInfo : all) {
                //生成邀请码 六位
                if (StringUtils.isEmpty(userInfo.getInvitationCode())) {
                    setInvitationCode(userInfo);
                } else {
                    Pattern pattern = Pattern.compile("[0-9]*");
                    Matcher isNum = pattern.matcher(userInfo.getInvitationCode());
                    if (!isNum.matches()) {
                        setInvitationCode(userInfo);
                    }
                }
            }
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "数据正在修改中！");
        }

    }

public void reGeneratePdd(PopClient client,UserInfo userInfo){
    PddDdkGoodsPidGenerateRequest request = new PddDdkGoodsPidGenerateRequest();
    request.setNumber(1L);
    CommonInfo one = commonRepository.findOne(104);
    request.setMediaId(Long.parseLong(one.getValue()));
    List<String> pIdNameList = new ArrayList<String>();
    pIdNameList.add(userInfo.getRelationId()+ DateFormatUtils.format(System.currentTimeMillis(),"yyyyMMddHHmmss"));
    request.setPIdNameList(pIdNameList);
    PddDdkGoodsPidGenerateResponse pddDdkGoodsPidGenerateResponse = null;
    try {
        pddDdkGoodsPidGenerateResponse = client.syncInvoke(request);
        PddDdkGoodsPidGenerateResponse.PIdGenerateResponse pIdGenerateResponse = pddDdkGoodsPidGenerateResponse.getPIdGenerateResponse();
        if (pIdGenerateResponse != null) {
            List<PddDdkGoodsPidGenerateResponse.PIdGenerateResponsePIdListItem> pIdList = pIdGenerateResponse.getPIdList();
            if (pIdList.size() > 0) {
                String pId = pIdList.get(0).getPId();
                Thread.sleep(1000);
                userInfo.setPdd(pId);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    @Override
    public Result findOne(long id) {
        UserInfo userInfo = userJpaRepository.findById(id).orElse(null);
        if (userInfo != null) {
            if (userInfo.getInvitation() == null) {
                CommonInfo one = commonRepository.findOne(4);
                if (one.getValue().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                    userInfo.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                }

            }
            if (StringUtils.isEmpty(userInfo.getNickName())) {
                if (StringUtils.isNotEmpty(userInfo.getPhone())) {
                    userInfo.setNickName(userInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                } else {
                    userInfo.setNickName("用户" + userInfo.getId());
                }
            }

            userInfo = userJpaRepository.save(userInfo);
            //生成邀请码 六位
            if (StringUtils.isEmpty(userInfo.getInvitationCode())) {
                setInvitationCode(userInfo);
            }
            iUserLogService.insertUserLog(id);
            //微信小程序处理
//            if (userInfo.getRelationId() == null) {
//                setRelation(userInfo);
//            }
            if (userInfo.getRelationId() != null) {
                if (StringUtils.isBlank(userInfo.getPdd())) {
                    //处理拼多多商品购买授权 生成推广位
                    CommonInfo clientId = commonRepository.findOne(23);
                    CommonInfo clientSecret = commonRepository.findOne(24);
                    PopClient client = new PopHttpClient(clientId.getValue() != null ? clientId.getValue() : Config.clientId, clientSecret.getValue() != null ? clientSecret.getValue() : Config.clientSecret);
                    PddDdkGoodsPidGenerateRequest request = new PddDdkGoodsPidGenerateRequest();
                    request.setNumber(1L);
                    CommonInfo one = commonRepository.findOne(104);
                    request.setMediaId(Long.parseLong(one.getValue()));
                    List<String> pIdNameList = new ArrayList<String>();
                    pIdNameList.add(userInfo.getRelationId());
                    request.setPIdNameList(pIdNameList);
                    PddDdkGoodsPidGenerateResponse pddDdkGoodsPidGenerateResponse = null;
                    try {
                        pddDdkGoodsPidGenerateResponse = client.syncInvoke(request);
                        PddDdkGoodsPidGenerateResponse.PIdGenerateResponse pIdGenerateResponse = pddDdkGoodsPidGenerateResponse.getPIdGenerateResponse();
                        if (pIdGenerateResponse != null) {
                            List<PddDdkGoodsPidGenerateResponse.PIdGenerateResponsePIdListItem> pIdList = pIdGenerateResponse.getPIdList();
                            if (pIdList.size() > 0) {
                                String pId = pIdList.get(0).getPId();
                                Thread.sleep(1000);
                                userInfo.setPdd(pId);
                            }
                        }
                        PopBaseHttpResponse.ErrorResponse errorResponse = pddDdkGoodsPidGenerateResponse.getErrorResponse();
                        if (errorResponse != null && errorResponse.getSubCode().equals("20003")) {
                            //名字只能注册一次，目前没有办法根据名字查pid,所以重新生成
                            reGeneratePdd(client,userInfo);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (StringUtils.isBlank(userInfo.getJd())) {
                    /**
                     * type 站点类型 1网站推广位2.APP推广位3.社交媒体推广位4.聊天工具推广位5.二维码推广
                     * unionType 1：cps推广位 2：cpc推广位
                     * siteID 站点ID，即网站ID/app ID/snsID ,当type传入4以外的值时，siteId为必填
                     *
                     * @param name
                     * @return
                     */
                    CommonInfo one = commonRepository.findOne(28);
                    String appid = Config.JD_APPID;
                    if (one != null) {
                        appid = one.getValue();
                    }
                    CommonInfo two = commonRepository.findOne(29);
                    String keyid = Config.KEYID;
                    if (one != null) {
                        keyid = two.getValue();
                    }
                    CommonInfo three = commonRepository.findOne(30);
                    String apkey = Config.MIAOYOUQUN_Key;
                    if (three != null) {
                        apkey = three.getValue();
                    }
                    CommonInfo types = commonRepository.findOne(86);
                    String type = "1";
                    if (types != null) {
                        type = types.getValue();
                    }
                    String s = HttpClient.doGet(Config.MIAOYOUQUN_URL + "/jingdong/createUnionPosition?apkey=" + apkey + "&key_id=" + keyid + "&spaceNameList=" + userInfo.getRelationId() + "&unionType=1&type=" + type + "&siteId=" + appid);
                    if (StringUtils.isNotBlank(s)) {
                        if (JSON.parseObject(s).getString("code").equals("200")) {
                            JSONObject jsonObject = JSON.parseObject(s);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (data != null) {
                                JSONObject orderResponse = data.getJSONObject("resultList");
                                if (orderResponse != null) {
                                    String string = orderResponse.getString(userInfo.getRelationId());
                                    userInfo.setJd(string);
                                }
                            }
                        } else {
                            logger.error(s);
                        }
                    }

                }
                UserInfo save = userJpaRepository.save(userInfo);
                return ResultUtil.success(save);
            }

        }

        return ResultUtil.success(userInfo);
    }

    private void setRelation(UserInfo userInfo) {
        int t = (int) ((Math.random() * 9 + 1) * 1000000);
        UserInfo relationId = userRepository.getUserByRelationId(String.valueOf(t));
        if (relationId == null) {
            userInfo.setRelationId(String.valueOf(t));
            userJpaRepository.save(userInfo);
        } else {
            setRelation(userInfo);
        }
    }

    @Override
    public void setInvitationCode(UserInfo userInfo) {
        int t = (int) ((Math.random() * 9 + 1) * 100000);
        UserInfo relationId = userRepository.getUserByInvitationCode(String.valueOf(t));
        if (relationId == null) {
            userInfo.setInvitationCode(String.valueOf(t));
            userJpaRepository.save(userInfo);
        } else {
            setInvitationCode(userInfo);
        }
    }

    @Override
    public Result delete(long id) {
        userJpaRepository.deleteById(id);
        return ResultUtil.success();
    }


    @Override
    public Result find(String phone, Pageable pageable) {
        return ResultUtil.success(userRepository.find(phone, pageable));
    }

    @Override
    public Result findList(Pageable pageable) {
        return ResultUtil.success(userJpaRepository.findAll(pageable));
    }

    @Override
    @Transactional
    public Result updateBody(UserInfo userInfo) {
        UserInfo foodBanner1 = userJpaRepository.findById(userInfo.getId()).orElse(null);
        assert foodBanner1 != null;
        BeanUtils.copyProperties(userInfo, foodBanner1);
        return ResultUtil.success();
    }

    @Override
    public Result loginByOpenId(String openid, String relation) {
        if (!StringUtils.isEmpty(openid)) {
            CommonInfo one = commonRepository.findOne(4);
            User wx = accountService.getUserInfo(openid);
            if (wx != null && wx.getUnionid() != null) {
                UserInfo userByUnionid = userRepository.getUserByUnionid(wx.getUnionid());
                if (userByUnionid != null) {
                    if (wx.getHeadimgurl() != null) {
                        userByUnionid.setImage_url(wx.getHeadimgurl());
                    }
                    if (wx.getSex() != null) {
                        userByUnionid.setGender(String.valueOf(wx.getSex()));
                    }
                    if (wx.getCity() != null) {
                        userByUnionid.setAddress(wx.getCity());
                    }
                    if (wx.getNickname() != null) {
                        userByUnionid.setNickName(wx.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                    userByUnionid.setOpenId(openid);
                    UserInfo save = userJpaRepository.save(userByUnionid);
                    return getResult(save);
                } else {
                    return wxLoginByOpenid(openid, relation, one);
                }
            } else {
                return wxLoginByOpenid(openid, relation, one);
            }

        } else {
            return ResultUtil.error(ExceptionEnum.LIMIT_USER);
        }

    }

    private Result wxLoginByOpenid(String openid, String relation, CommonInfo one) {
        UserInfo userByWxId = userRepository.getUserByWxId(openid);
        User wx = accountService.getUserInfo(openid);
        if (userByWxId == null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            UserInfo userInfo = new UserInfo();
            userInfo.setPwd(MD5Util.encoderByMd5("123456"));
            userInfo.setJifen("0");
            userInfo.setGrade(commonRepository.findOne(40).getValue());
            userInfo.setOrderJifen("0");
            if (relation != null) {
                if (relation.length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(relation);
                    userInfo.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo.setInvitation(relation);
                }
            } else {
                if (one.getValue().length() == 6) {
                    UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                    userInfo.setInvitation(userByInvitationCode.getRelationId());
                } else {
                    userInfo.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                }
            }
            userInfo.setIsInvitation(1);
            userInfo.setCreateAt(time);
            userInfo.setPlatform("weixin");
            userInfo.setState("true");
            if (wx.getHeadimgurl() != null) {
                userInfo.setImage_url(wx.getHeadimgurl());
            }
            if (wx.getSex() != null) {
                userInfo.setGender(String.valueOf(wx.getSex()));
            }
            if (wx.getCity() != null) {
                userInfo.setAddress(wx.getCity());
            }
            if (wx.getNickname() != null) {
                userInfo.setNickName(wx.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));

            }
            if (wx.getUnionid() != null) {
                userInfo.setUnionid(wx.getUnionid());
            }
            userInfo.setOpenId(openid);
            UserInfo save = userJpaRepository.saveAndFlush(userInfo);
            if (relation != null) {
                checkRelationInvitation(relation, userInfo.getNickName());
            }
            return getResult(save);
        }
        if (!userByWxId.getState().equals("true")) {
            return ResultUtil.error(ExceptionEnum.LIMIT_USER);
        }
        UserInfo save = getWx(openid, userByWxId);
        return getResult(save);
    }

    @Override
    public Result loginByMpId(String openids) {
        CommonInfo one = commonRepository.findOne(4);
        UserInfo userByMpId = userRepository.getUserByMpId(openids);
        if (userByMpId == null) {
            User wx = accountService.getUserInfo(openids);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            UserInfo userInfo = new UserInfo();
            userInfo.setPwd(MD5Util.encoderByMd5("123456"));
            userInfo.setJifen("0");
            userInfo.setGrade(commonRepository.findOne(40).getValue());
            userInfo.setOrderJifen("0");
            if (one.getValue().length() == 6) {
                UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                userInfo.setInvitation(userByInvitationCode.getRelationId());
            } else {
                userInfo.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
            }
            userInfo.setIsInvitation(1);
            userInfo.setCreateAt(time);
            userInfo.setPlatform("mp");
            userInfo.setState("true");
            userInfo.setMpId(openids);
            UserInfo save = userJpaRepository.save(userInfo);
            return getResult(save);
        }
        if (!userByMpId.getState().equals("true")) {
            return ResultUtil.error(ExceptionEnum.LIMIT_USER);
        }
        return getResult(userByMpId);
    }


    @Override
    public Result loginByOpenIdWithRelation(String openid, String relation) {
        logger.error("loginByOpenIdWithRelation----" + openid);
        CommonInfo one = commonRepository.findOne(4);
        UserInfo userByWxId = userRepository.getUserByWxId(openid);
        if (userByWxId == null) {
            logger.error("userByWxId is null----" + relation);
            User wx = accountService.getUserInfo(openid);
            if (wx.getNickname() != null) {
                logger.error("getUserInfo ----" + wx.getNickname());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(new Date());
                UserInfo userInfo = new UserInfo();
                userInfo.setGrade(commonRepository.findOne(40).getValue());
                if (relation == null) {
                    if (one.getValue().length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                        userInfo.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userInfo.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                    }

                } else {
                    if (relation.length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(relation);
                        userInfo.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userInfo.setInvitation(relation);
                    }
                }
                if (wx.getHeadimgurl() != null) {
                    userInfo.setImage_url(wx.getHeadimgurl());
                }
                if (wx.getSex() != null) {
                    userInfo.setGender(String.valueOf(wx.getSex()));
                }
                if (wx.getCity() != null) {
                    userInfo.setAddress(wx.getCity());
                }
                if (wx.getNickname() != null) {

                    userInfo.setNickName(wx.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                userInfo.setPwd(MD5Util.encoderByMd5("123456"));
                userInfo.setJifen("0");
                userInfo.setOrderJifen("0");
                userInfo.setIsInvitation(1);
                userInfo.setPlatform("weixin");
                userInfo.setCreateAt(time);
                userInfo.setState("true");
                userInfo.setOpenId(openid);
                UserInfo save = userJpaRepository.saveAndFlush(userInfo);
                if (relation != null) {
                    checkRelationInvitation(relation, userInfo.getNickName());
                }
                return getResult(save);
            } else {
                return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
            }
        }
        if (!userByWxId.getState().equals("true")) {
            return ResultUtil.error(ExceptionEnum.LIMIT_USER);
        }
        UserInfo save = getWx(openid, userByWxId);
        return getResult(save);
    }

    @Override
    public Result getResult(UserInfo userInfo) {
        if (userInfo.getState().equals("false")) {
            return ResultUtil.error(ExceptionEnum.LIMIT_USER);
        }
        if (StringUtils.isEmpty(userInfo.getGradeIndex())) {
            //如果没有等级 则取一级
            Member member = memberRepository.findMemberByGradeIndex(1);
            if (member != null) {
                userInfo.setGrade(member.getRate());
                userInfo.setZhiRate(member.getZhiRate());
                userInfo.setFeiRate(member.getFeiRate());
                userInfo.setGradeIndex(String.valueOf(member.getGrade()));
                userInfo.setGradeTime(DateUtil.createTime());
                userInfo = userJpaRepository.save(userInfo);
            }
        }
        Token byUserIds = tokenRepository.findByUserId(String.valueOf(userInfo.getId()));
        if (byUserIds == null) {
            String uuid = UUID.randomUUID().toString();
            Token token = new Token();
            token.setUserId(String.valueOf(userInfo.getId()));
            token.setUuid(uuid);
            Token save = tokenJpaRepository.save(token);
            return ResultUtil.success(save);
        }
        return ResultUtil.success(byUserIds);
    }

    @Override
    public Result Login(LoginInfo loginInfo) {
        try {
            UserInfo userByPhone = userRepository.getUserByPhone(loginInfo.getPhone());
            if (userByPhone == null) {
                return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
            }
            UserInfo login = userRepository.login(loginInfo.getPhone());
            if (login == null) {
                return ResultUtil.error(ExceptionEnum.USER_PWD_ERROR);
            }
            if (login.getPwd() == null) {
                return ResultUtil.error(ExceptionEnum.USER_PWD_ERROR);
            }
            if (!MD5Util.checkMD5(loginInfo.getPwd(), login.getPwd())) {
                return ResultUtil.error(ExceptionEnum.USER_PWD_ERROR);
            }
            return getResult(login);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ExceptionEnum.ERROR);
        }
    }

    @Override
    public Result mpUpdateUser(LoginInfo loginInfo) {
        System.err.println(JsonUtil.toJSONString(loginInfo));
        CommonInfo one = commonRepository.findOne(4);
        if (loginInfo.getUnionid() != null && !loginInfo.getUnionid().equals("-1")) {
            UserInfo userInfo = userRepository.getUserByUnionid(loginInfo.getUnionid());
            if (userInfo != null) {
                if (StringUtils.isNotEmpty(loginInfo.getImageUrl()) && StringUtils.isEmpty(userInfo.getImage_url())) {
                    userInfo.setImage_url(loginInfo.getImageUrl());
                }
                if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                    userInfo.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }

                userInfo.setMpId(loginInfo.getOpenid());
                UserInfo save = userJpaRepository.save(userInfo);
                return getResult(save);
            } else {
                loginInfo = isInvitaionCode(one, loginInfo);
                if (loginInfo == null) {
                    return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(new Date());
                UserInfo userInfo1 = new UserInfo();
                if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                    userInfo1.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                if (loginInfo.getInvitation() != null) {
                    if (loginInfo.getInvitation().length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                        userInfo1.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userInfo1.setInvitation(loginInfo.getInvitation());
                    }
                } else {
                    if (one.getValue().length() == 6) {
                        UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                        userInfo1.setInvitation(userByInvitationCode.getRelationId());
                    } else {
                        userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                    }
                }
                userInfo1.setPwd(MD5Util.encoderByMd5("123456"));
                userInfo1.setIsInvitation(1);
                userInfo1.setJifen("0");
                userInfo1.setPlatform("mp");
                userInfo1.setOrderJifen("0");
                if (StringUtils.isNotEmpty(loginInfo.getImageUrl()) && StringUtils.isEmpty(userInfo1.getImage_url())) {
                    userInfo1.setImage_url(loginInfo.getImageUrl());
                }
                userInfo1.setUnionid(loginInfo.getUnionid());
                userInfo1.setMpId(loginInfo.getOpenid());
                userInfo1.setGrade(commonRepository.findOne(40).getValue());
                userInfo1.setCreateAt(time);
                userInfo1.setState("true");
                UserInfo save = userJpaRepository.saveAndFlush(userInfo1);
                if (loginInfo.getInvitation() != null) {
                    checkRelationInvitation(loginInfo.getInvitation(), userInfo1.getNickName());
                }
                return getResult(save);
            }
        } else {
            if (loginInfo.getOpenid() != null) {
                UserInfo userByPhone = null;
                if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                    userByPhone = userRepository.getUserByPhone(loginInfo.getPhone());
                }
                if (userByPhone != null) {
                    UserInfo userInfo = userRepository.getUserByMpId(loginInfo.getOpenid());
                    if (userInfo != null) {
                        userJpaRepository.deleteById(userInfo.getId());
                    }
                    userByPhone.setMpId(loginInfo.getOpenid());
                    if (StringUtils.isNotEmpty(loginInfo.getNickName()) && StringUtils.isEmpty(userByPhone.getNickName())) {
                        userByPhone.setNickName(loginInfo.getNickName());
                    }
                    if (StringUtils.isNotEmpty(loginInfo.getImageUrl()) && StringUtils.isEmpty(userByPhone.getImage_url())) {
                        userByPhone.setImage_url(loginInfo.getImageUrl());
                    }

                    UserInfo save = userJpaRepository.save(userByPhone);
                    return getResult(save);
                } else {
                    UserInfo userInfo = userRepository.getUserByMpId(loginInfo.getOpenid());
                    if (userInfo != null) {
                        if (StringUtils.isNotEmpty(loginInfo.getImageUrl()) && StringUtils.isEmpty(userInfo.getImage_url())) {
                            userInfo.setImage_url(loginInfo.getImageUrl());
                        }

                        if (StringUtils.isNotEmpty(loginInfo.getNickName()) && StringUtils.isEmpty(userInfo.getNickName())) {
                            userInfo.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                        }
                        if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                            userInfo.setPhone(loginInfo.getPhone());
                        }
                        userInfo.setUnionid(loginInfo.getUnionid());
                        UserInfo save = userJpaRepository.save(userInfo);
                        return getResult(save);
                    }
                    loginInfo = isInvitaionCode(one, loginInfo);
                    if (loginInfo == null) {
                        return ResultUtil.error(ExceptionEnum.CODE_NOT_FOUND);
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = simpleDateFormat.format(new Date());
                    UserInfo userInfo1 = new UserInfo();
                    if (StringUtils.isNotEmpty(loginInfo.getNickName())) {
                        userInfo1.setNickName(loginInfo.getNickName().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                    if (loginInfo.getInvitation() != null) {
                        if (loginInfo.getInvitation().length() == 6) {
                            UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(loginInfo.getInvitation());
                            userInfo1.setInvitation(userByInvitationCode.getRelationId());
                        } else {
                            userInfo1.setInvitation(loginInfo.getInvitation());
                        }
                    } else {
                        if (one.getValue().length() == 6) {
                            UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(one.getValue());
                            userInfo1.setInvitation(userByInvitationCode.getRelationId());
                        } else {
                            userInfo1.setInvitation(one.getValue() != null ? one.getValue() : Config.publicRelation);
                        }
                    }
                    if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
                        userInfo1.setPhone(loginInfo.getPhone());
                    }
                    userInfo1.setPwd(MD5Util.encoderByMd5("123456"));
                    userInfo1.setIsInvitation(1);
                    userInfo1.setJifen("0");
                    userInfo1.setImage_url(loginInfo.getImageUrl());
                    userInfo1.setPlatform("mp");
                    userInfo1.setOrderJifen("0");
                    userInfo1.setMpId(loginInfo.getOpenid());
                    userInfo1.setGrade(commonRepository.findOne(40).getValue());
                    userInfo1.setCreateAt(time);
                    userInfo1.setState("true");
                    UserInfo save = userJpaRepository.saveAndFlush(userInfo1);
                    if (loginInfo.getInvitation() != null) {
                        checkRelationInvitationMp(loginInfo.getInvitation(), userInfo1.getNickName());
                    }
                    return getResult(save);
                }

            }
        }
        return ResultUtil.error(-1, "登录失败！");
    }

    @Override
    public UserInfo getUserByPhone(String userName) {
        return userRepository.getUserByPhone(userName);
    }

    @Override
    public UserInfo getUserInfoByAppleUserId(String appleUserId) {
        return userRepository.getUserInfoByAppleUserId(appleUserId);
    }

    @Override
    public Result getUserByWxId(String wxId) {
        return ResultUtil.success(userRepository.getUserByWxId(wxId));
    }

    @Override
    public Result getUserByRelationId(String relationId) {
        return ResultUtil.success(userRepository.getUserByRelationId(relationId));
    }

    @Override
    @Transactional
    public Result updateState(String state, String id) {
        Integer adminInfo = userRepository.updateState(state, Long.parseLong(id));
        if (adminInfo == 1) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ExceptionEnum.STATE_PWD_ERROR);
        }
    }

    @Override
    @Transactional
    public Result updatePwd(String old, String pwd, String userId) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        if (one == null) {
            return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
        }
        if (!one.getPwd().equals(old)) {
            return ResultUtil.error(ExceptionEnum.OLD_PWD_ERROR);
        }
        if (one.getPwd().equals(pwd)) {
            return ResultUtil.error(ExceptionEnum.OLD_NOT_SAME_NEW_PWD_ERROR);
        }
        return ResultUtil.success(userRepository.updatePwd(pwd, userId));
    }


    @Override
    public Result forgetPwd(String pwd, String phone, String msg) {
        try {
            Msg byPhoneAndCode = msgJpaRepository.findByPhoneAndCode(phone, msg);
            //校验短信验证码
            if (byPhoneAndCode == null) {
                return ResultUtil.error(ExceptionEnum.CODE_ERROR);
            }
            UserInfo userByPhone = userRepository.getUserByPhone(phone);
            userByPhone.setPwd(MD5Util.encoderByMd5(pwd));
            msgJpaRepository.deleteById(byPhoneAndCode.getId());
            userJpaRepository.save(userByPhone);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ExceptionEnum.ERROR);
        }
    }

    @Override
    public Result LoginAndRegister(LoginInfo loginInfo) {
        return null;
    }

    @Override
    public Result loginAndCode(LoginInfo loginInfo) {
        return null;
    }

    @Override
    public Result checkRelationInvitations(String invitation, String name) {
        checkRelationInvitation(invitation, name);
        return ResultUtil.success();
    }

    //微信小程序
    private void checkRelationInvitationMp(String invitation, String name) {
        String count = userRepository.getCount(invitation);
        Member member = memberService.findMemberByPeopleNum(Integer.parseInt(count));
        UserInfo userByRelationId = userRepository.getUserByRelationId(invitation);
        if (userByRelationId != null) {
            if (member != null) {
                userByRelationId.setGrade(member.getRate());
                userByRelationId.setZhiRate(member.getZhiRate());
                userByRelationId.setFeiRate(member.getFeiRate());
                userByRelationId.setGradeIndex(String.valueOf(member.getGrade()));
                userByRelationId.setGradeTime(DateUtil.createTime());
                userJpaRepository.save(userByRelationId);
            }
            User wx = accountService.getUserInfo(userByRelationId.getOpenId());
            String openId = null;
            if (wx != null) {
                openId = wx.getOpenid();
            }
            invitationSuccess(openId, name, userByRelationId.getId());
        }
    }

    private void checkRelationInvitation(String invitation, String name) {
        checkRelationInvitationMp(invitation, name);
    }

    /**
     * 好友邀请成功提醒
     */
    private void invitationSuccess(String openId, String name, Long userId) {
        UserInfo userById = userRepository.getUserById(userId);
        if (userById != null) {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(5));
            messageInfo.setContent("你的团队有新成员加入啦！！" + name);
            messageInfo.setTitle("团队成员加入提醒");
            messageInfo.setUserName(userById.getNickName());
            messageInfo.setUserId(String.valueOf(userById.getId()));
            iMessageService.saveBody(messageInfo);
        }

        UserInfo userByWxId = userRepository.getUserByWxId(openId);
        User userInfo = accountService.getUserInfo(openId);
        if (userByWxId != null && userInfo != null && userInfo.getNickname() != null) {


//            CommonInfo three = commonRepository.findOne(33);
            if (userByWxId.getClientid() != null) {
                pushToSingle("团队成员加入提醒", "你的团队有新成员加入啦！！" + name, userByWxId.getClientid());
            }
            /*String apkey = Config.InvitaionNotification;
            if (three != null) {
                apkey = three.getValue();
            }

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            CommonInfo urls = commonRepository.findOne(19);
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("first", new TemplateMessageItem("你的团队有新成员加入啦！！", "#d71345"));
            data.put("keyword1", new TemplateMessageItem(name, "#d71345"));
            data.put("keyword2", new TemplateMessageItem(name, "#d71345"));
            data.put("keyword3", new TemplateMessageItem(sdf1.format(new Date()), "#d71345"));
            data.put("remark", new TemplateMessageItem("点击查看详情进入【我的】-【团队成员】-查看", null));
            accountService.sendWxMessage(apkey, data, openId, urls.getValue() + "/pages/member/user");*/

        }
    }

    /**
     * 会员升级提醒
     */
    private void totalSuccess(String openId, Integer dengji, Integer number) {
        UserInfo userByWxId = userRepository.getUserByWxId(openId);
        User userInfo = accountService.getUserInfo(openId);
        if (userByWxId != null && userInfo != null && userInfo.getNickname() != null) {
            MessageInfo messageInfo = new MessageInfo();
            CommonInfo urls = commonRepository.findOne(19);
            CommonInfo three = commonRepository.findOne(36);
            String apkey = Config.ShengjiNotification;
            if (three != null) {
                apkey = three.getValue();
            }
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            if (number <= 0) {
                messageInfo.setContent("恭喜你已经成为超级VIP啦！！已享有超级VIP的福利，拥有最高返佣特权哦");
                messageInfo.setTitle("会员等级提升");
                if (userByWxId.getClientid() != null) {
                    pushToSingle("会员等级提升", "恭喜你已经成为超级VIP啦！！已享有超级VIP的福利，拥有最高返佣特权哦", userByWxId.getClientid());
                }
                data.put("thing2", new TemplateMessageItem("恭喜你已经成为超级VIP啦！！", "#d71345"));
                data.put("thing9", new TemplateMessageItem(userByWxId.getNickName(), "#d71345"));
            } else {
                messageInfo.setContent("恭喜你，你的会员等级提升啊！！再邀请【" + number + "人】到达最高等级享受最高佣金");
                messageInfo.setTitle("会员等级提升");
                if (userByWxId.getClientid() != null) {
                    pushToSingle("会员等级提升", "恭喜你，你的会员等级提升啊！！！！再邀请【" + number + "人】到达最高等级享受最高佣金", userByWxId.getClientid());
                }
                data.put("first", new TemplateMessageItem("恭喜你，你的会员等级提升啊！！", "#d71345"));
                data.put("keyword1", new TemplateMessageItem("VIP" + dengji, "#d71345"));

                data.put("keyword2", new TemplateMessageItem("再邀请【" + number + "人】到达最高等级享受最高佣金", "#d71345"));

                data.put("thing2", new TemplateMessageItem("恭喜你,已经成为VIP" + dengji, "#d71345"));
                data.put("thing9", new TemplateMessageItem(userByWxId.getNickName(), "#d71345"));
            }
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);

            accountService.sendWxMessage(apkey, data, openId, urls.getValue() + "/pages/member/user");

        }
    }

    /**
     * 对单个用户推送消息
     * <p>
     * 场景1：某用户发生了一笔交易，银行及时下发一条推送消息给该用户。
     * <p>
     * 场景2：用户定制了某本书的预订更新，当本书有更新时，需要向该用户及时下发一条更新提醒信息。
     * 这些需要向指定某个用户推送消息的场景，即需要使用对单个用户推送消息的接口。
     */
   /* @Override
    public void pushToSingle(String title, String content, String clientId) {

        IGtPush push = new IGtPush(commonRepository.findOne(60).getValue(), commonRepository.findOne(62).getValue());

        NotificationTemplate template = new NotificationTemplate();

        // 设置APPID与APPKEY
        template.setAppId(commonRepository.findOne(61).getValue());
        template.setAppkey(commonRepository.findOne(60).getValue());

        //设置展示样式
        Style0 style = new Style0();
        // 设置通知栏标题与内容

        style.setTitle(title);
        style.setText(content);
        // 配置通知栏图标
        style.setLogo("icon.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
        // 配置通知栏网络图标
        style.setLogoUrl(commonRepository.findOne(19).getValue() + "/logo.png");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        style.setChannel(String.valueOf(number));
        style.setChannelName(Config.BASE_NAME);
        style.setChannelLevel(4); //设置通知渠道重要性
        template.setStyle(style);
        template.setTransmissionType(1);  // 透传消息设置，收到消息是否立即启动应用： 1为立即启动，2则广播等待客户端自启动
        template.setTransmissionContent(content);
        template.setNotifyid(number); // 在消息推送的时候设置notifyid。如果需要覆盖此条消息，则下次使用相同的notifyid发一条新的消息。客户端sdk会根据notifyid进行覆盖。
        number = number + 1;
        // 单推消息类型
        SingleMessage message = new SingleMessage();

        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(72 * 3600 * 1000);
        message.setPushNetWorkType(0); // 判断客户端是否wifi环境下推送。1为仅在wifi环境下推送，0为不限制网络环境，默认不限
        // APNs下发策略；1: 个推通道优先，在线经个推通道下发，离线经APNs下发(默认);2: 在离线只经APNs下发;3: 在离线只经个推通道下发;4: 优先经APNs下发，失败后经个推通道下发;
        message.setStrategyJson("{\"ios\":4}");
        Target target = new Target();

        target.setAppId(commonRepository.findOne(61).getValue());
        target.setClientId(clientId);
        IPushResult ret = null;
        try {

            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }

    }*/
    @Override
    public int updateUserClientIdIsNull(String clientid) {
        return userRepository.updateUserClientIdIsNull(clientid);
    }

    @Override
    public void pushToSingle(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserInfo userEntity = userRepository.getUserByClientid(clientId);
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                apiConfiguration.setAppId(commonRepository.findOne(61).getValue());
                apiConfiguration.setAppKey(commonRepository.findOne(60).getValue());
                apiConfiguration.setMasterSecret(commonRepository.findOne(62).getValue());
                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    GTNotification notification = new GTNotification();
                    pushDTO.setPushMessage(pushMessage);
                    // 配置通知栏图标
                    notification.setLogo(commonRepository.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                    // 配置通知栏网络图标
                    notification.setLogoUrl(commonRepository.findOne(19).getValue() + "/logo.png");
                    notification.setTitle(title);
                    notification.setBody(content);
                    notification.setClickType("startapp");
                    notification.setUrl(commonRepository.findOne(19).getValue());
                    notification.setChannelLevel("3");
                    pushMessage.setNotification(notification);
                } else {
                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                }
                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.error("消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("消息推送成功失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }


    /**
     * 自营商城订单通知
     *
     * @param userId     用户id
     * @param orderNum   订单号
     * @param payMoney   支付金额
     * @param createTime 下单时间
     */
    @Override
    public void orderPay(Long userId, String orderNum, String payMoney, String createTime) {
        UserInfo user = userRepository.getUserById(userId);
        String openId = user.getOpenId();
        if (user != null && user.getOpenId() != null) {
            CommonInfo urls = commonRepository.findOne(19); //域名
            String templateId = commonRepository.findOne(256).getValue(); //消息模板
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string2", new TemplateMessageItem(orderNum, "#d71345"));
            data.put("thing3", new TemplateMessageItem("订单通知", "#d71345"));
            data.put("time4", new TemplateMessageItem(createTime, "#d71345"));
            accountService.sendWxMessage(templateId, data, openId, urls.getValue() + "/pages/zysc/my/myList#/pages/zysc/my/myList");
        }
    }

    @Override
    public void orderCancel(Long userId, String orderNum, String time) {
        UserInfo user = userRepository.getUserById(userId);
        String openId = user.getOpenId();
        if (user != null && user.getOpenId() != null) {
            CommonInfo urls = commonRepository.findOne(19); //域名
            String templateId = commonRepository.findOne(96).getValue(); //消息模板
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string1", new TemplateMessageItem(orderNum, "#d71345"));
            data.put("thing8", new TemplateMessageItem(user.getNickName(), "#d71345"));
            accountService.sendWxMessage(templateId, data, openId, urls.getValue() + "/pages/zysc/my/myList#/pages/zysc/my/myList");
        }
    }

    @Override
    public void orderExpress(Long userId, String orderNum, String time, String expressName, String expressNumber, String address) {
        UserInfo user = userRepository.getUserById(userId);
        String openId = user.getOpenId();
        if (user != null && user.getOpenId() != null) {
            CommonInfo urls = commonRepository.findOne(19); //域名
            String templateId = commonRepository.findOne(97).getValue(); //消息模板
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string2", new TemplateMessageItem(orderNum, "#d71345"));
            data.put("thing13", new TemplateMessageItem(expressName, "#d71345"));
            data.put("character_string14", new TemplateMessageItem(expressNumber, "#d71345"));
            data.put("thing19", new TemplateMessageItem(address, "#d71345"));
            accountService.sendWxMessage(templateId, data, openId, urls.getValue() + "/pages/zysc/my/myList#/pages/zysc/my/myList");
            //订单消息
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("4");
            messageInfo.setTitle("订单发货成功");
            messageInfo.setContent("订单编号：" + orderNum + "，发货时间：" + time + "，快递公司：" + expressName + "，快递单号:" + expressNumber + "，收货地址：" + address);
            messageInfo.setUserName(user.getNickName());
            messageInfo.setUserId(userId.toString());
            iMessageService.saveBody(messageInfo);
        }
    }

    @Override
    public void orderRefund(Long userId, String payMoney, String ordersNum) {
        UserInfo user = userRepository.getUserById(userId);
        String openId = user.getOpenId();
        if (user != null && user.getOpenId() != null) {
            CommonInfo urls = commonRepository.findOne(19); //域名
            String templateId = commonRepository.findOne(98).getValue(); //消息模板
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string5", new TemplateMessageItem(ordersNum, "#d71345"));
            data.put("amount2", new TemplateMessageItem(payMoney, "#d71345"));
            data.put("thing3", new TemplateMessageItem("原路退回", "#d71345"));
            accountService.sendWxMessage(templateId, data, openId, urls.getValue() + "/pages/zysc/my/myList#/pages/zysc/my/myList");
            //订单消息
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("4");
            messageInfo.setTitle("订单退款成功");
            messageInfo.setContent("退款金额：" + payMoney + "退款方式：原路退回，退款时间：具体到账时间以收到时间为准");
            messageInfo.setUserName(user.getNickName());
            messageInfo.setUserId(userId.toString());
            iMessageService.saveBody(messageInfo);
        }

    }

    @Override
    public UserInfo getUserByUserId(String userId) {
        return userJpaRepository.getOne(Long.valueOf(userId));
    }

    @Override
    public void updateHelpTaskUserById(UserInfo userInfo) {
        userRepository.updateHelpTaskUserById(userInfo);
    }

    @Override
    public void deleteById(Long id) {
        userJpaRepository.deleteById(id);
    }

    @Override
    public void deleteByIdList(String ids) {
        String[] id = ids.split(",");
        for (String i : id) {
            userJpaRepository.deleteById(Long.parseLong(i));
        }
    }


    @Override
    public Result findByPhoneAndSysUser(String phone, Pageable pageable) {
        return ResultUtil.success(userRepository.findByPhoneAndSysUser(phone, pageable));
    }

    @Override
    public Result findListByTwo(Pageable pageable) {
        return ResultUtil.success(userRepository.findListByTwo(pageable));
    }

    /**
     * 获取小程序带参二维码
     * @param page 主页面
     * @param scene 参数拼接
     * @param width 二维码宽度
     * @param response 返回照片
     * @return
     */
    @Override
    public Result getImg(String page, String scene,String width, HttpServletResponse response){
        //获取access_token
        String appid = commonRepository.findOne(45).getValue();
        String secret = commonRepository.findOne(46).getValue();
        String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String s = HttpClient.doGet(url1);
        JSONObject j = JSONObject.parseObject(s);
        String access_token = j.get("access_token").toString();
        //获取二维码数据
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        Map<String,Object> map = Maps.newHashMap();
        map.put("scene",scene);
        map.put("page",page);
        map.put("width", width);
        String jsonString = JSON.toJSONString(map);
        InputStream inputStream = sendPostBackStream(url, jsonString);
        //生成二维码图片
        response.setContentType("image/png");
        try{
            BufferedImage bi = ImageIO.read(inputStream);
            ImageIO.write(bi, "JPG", response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultUtil.success();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     */
    public static InputStream sendPostBackStream(String url, String param) {
        PrintWriter out = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //解决乱码问题
            OutputStreamWriter outWriter =new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out =new PrintWriter(outWriter);
            // 发送请求参数
            if(StringUtils.isNotBlank(param)) {
                out.print(param);
            }
            // flush输出流的缓冲
            out.flush();
            return conn.getInputStream();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        } finally{
            IOUtils.closeQuietly(out);
        }
        return null;
    }


}
